/*
* Creater: Truongdv
* Date:14/12/2012
* Idea: Class xu ly du lieu xml
*/
var System_Xml= function(dirxml, fnLoadList){    
    this.dirxml = dirxml;				//
    this.xml ='';
    this.identity = 0;
    this.loadfile();
    this.htmlexport = '';
    this.row_index = '';
    this.v_current_style_name = '';
    this.v_id_column = '';
    // this.v_onclick_up = '';
    this.v_onclick = '';
    this.v_ondblclick = '';
    // this.v_onclick_down = '';
    this.v_have_move = '';
    this.v_table = '';
    this.v_pk_column = '';
    this.v_filename_column = '';
    this.content_column = '';
    this.v_append_column = '';
    this.p_arr_item = '';
    this.display_option = '';
    this.url_exec = '';
    this.pClassname = '';
    this.objectId = '';
    this.v_width = '';
    this.v_label = '';
    this.v_align = '';
    this.columnName = '';
    this.alias_name = '';
    this.xmlData = '';
    this.xmlTagInDb = '';
    this.v_value = '';
    this.tablename = '';
    this.datasearch = false;  
    this.oClass ='';
    this.markstar = 0;
    this.utilities = false;
    this.phpfunction = '';
    this.modaldialog = false;
    if(fnLoadList != '' && typeof(fnLoadList) !=='undefined')
        this.functionload = fnLoadList;
    else
        this.functionload = 'myClass.loadList()';    
}
System_Xml.prototype.loadfile = function(){
    var efy_xml = this;
    $.ajax({
        type: "GET",
        url: this.dirxml,
        dataType: "xml",
        success: function(xml) {
            efy_xml.xml = xml;
        }
    })
}
/*
* @author: Truongdv
* @since:17/12/2012
* @todo: Xuat man hinh danh sach
* Param: 	- arrResult: Mang du lieu can xuat ra
			- objupdate: Doi tuong can update toi
			- v_pk_column: Key cua col
*/
System_Xml.prototype.exportTable = function(arrResult,v_pk_column,objupdate,fulltextsearch,frm,addrow){
    if (typeof(addrow)==='undefined') {
        addrow = true;
    };
    var classXml = this;
    if(typeof(this.xml) !=='object'){
        setTimeout(function() {
            classXml.exportTable(arrResult,v_pk_column,objupdate,fulltextsearch,frm);
        }, 100);
    }else{
        classXml.generalTable(arrResult,v_pk_column,objupdate,fulltextsearch,frm,addrow);
    }
}
/**
*@author: HUNGVM
*@since: 19/05/2013
*@todo: get value in xml string
*@param
*   + sXmlString: Chuỗi XML lấy trong CSDL
*   + sXmlParentTag: Thẻ cha (mặc định là "data_list")
*   + sXmlTag:Thẻ lưu giá trị
*/
System_Xml.prototype._xmlGetXmlTagValue = function(sXmlString, sXmlParentTag, sXmlTag){
    var valueReturn = "";//create default variable
    $(sXmlString).find(sXmlParentTag).each(function () {
        valueReturn = $(this).find(sXmlTag).text()
    });
    return valueReturn;
}
/**
*@author: HUNGVM
*@since: 20/05/2013
*@todo: Chuyển đổi kiểu dữ liệu "năm-tháng-ngày h:m:s" trong CSDL ra "ngày/tháng/năm h:m:s"
*@param
*   + sDateTimeValue: Giá trị datetime
*/
System_Xml.prototype._yyyymmddToDDmmyyyyhhmm = function(sDateTimeValue){
    var sReturnDate = "";
    var dateTimeSplit = sDateTimeValue.split(' ');
    var dateSplit = dateTimeSplit[0].split('-');    
    var currentDate =  dateSplit[2]  + '/' + dateSplit[1] + '/' + dateSplit[0];
    //Get time
    var currentTime = dateTimeSplit[1];
    if (currentTime != ""){
        sReturnDate = currentDate + " " + currentTime;
    }
    return sReturnDate;
}

System_Xml.prototype._yyyymmddToDDmmyyyy = function(sDateTimeValue){
    var sReturnDate = "";
    var dateTimeSplit = sDateTimeValue.split(' ');
    var dateSplit = dateTimeSplit[0].split('-');    
    var currentDate =  dateSplit[2]  + '/' + dateSplit[1] + '/' + dateSplit[0];
    /*//Get date
    var now = new Date();
    var outStr = now.getHours()+':'+now.getMinutes()+':'+now.getSeconds();
    sReturnDate = currentDate + " " + outStr;*/
    return sReturnDate;
}

System_Xml.prototype._ddmmyyyyToYYyymmdd = function(sDateTimeValue){
    var sReturnDate = "";
    var dateTimeSplit = sDateTimeValue.split(' ');
    var dateSplit = dateTimeSplit[0].split('/');    
    var currentDate =  dateSplit[2]  + '-' + dateSplit[1] + '-' + dateSplit[0];   
    /*//Get time
    var currentTime = dateTimeSplit[1];    
    if (typeof(currentTime) === 'undefined') currentTime = '';
    if (currentTime != ""){
        sReturnDate = currentDate + " " + currentTime;
    }else{
        sReturnDate = currentDate;
    }      */
    return sReturnDate;
}

System_Xml.prototype._ddmmyyyyToYYyymmddhhmm = function(sDateTimeValue){
    var sReturnDate = "";
    var dateTimeSplit = sDateTimeValue.split(' ');
    var dateSplit = dateTimeSplit[0].split('/');    
    var currentDate =  dateSplit[2]  + '-' + dateSplit[1] + '-' + dateSplit[0];
    //Get date
    var now = new Date();
    var outStr = now.getHours()+':'+now.getMinutes()+':'+now.getSeconds();
    sReturnDate = currentDate + " " + outStr;
    return sReturnDate;
}

//Generate column of table structure
System_Xml.prototype.generalTable = function(arrResult,v_pk_column,objupdate,fulltextsearch,frm,addrow){   
    var efy_xml = this,count_column = '',colspan = 0, xmlString = '';
    var hdn_columnName = $('#hdn_columnName').val();
    var hdn_orderby = $('#hdn_orderby').val(),classtemp = 'headerdf';
    efy_xml.v_pk_column = v_pk_column;
    efy_xml.htmlexport = '';
    var xml = this.xml, iTotalRecord = arrResult.length;
    efy_xml.htmlexport += '<table class="list-table-data" cellpadding="0" cellspacing="0" border="0" align="center" id="table-data">';
    var psHtmlTempWidth = '', psHtmlTempLabel = '', v_type = '';
    $(xml).find('list_body col').each(function(){
        classtemp = 'headerdf';
        efy_xml.v_width = $(this).find('width').text();
        efy_xml.v_label = $(this).find('label').text();
        efy_xml.datasearch = $(this).find('datasearch').text();
        if(typeof(efy_xml.datasearch) ==='undefined' || efy_xml.datasearch ==='undefined') efy_xml.datasearch = false;        
        psHtmlTempWidth += '<col width="'+ efy_xml.v_width +'">';
        // Neu la du lieu search thi cho phep sort
        if(efy_xml.datasearch ==='true'){
            efy_xml.xmlData = $(this).find('xml_data').text();
            if (typeof(efy_xml.xmlData) ==='undefined') efy_xml.xmlData='false';//Default get data in column name
            efy_xml.columnName = $(this).find('column_name').text();
            if (typeof(efy_xml.columnName) ==='undefined') efy_xml.columnName='';
            efy_xml.xmlTagInDb = $(this).find('xml_tag_in_db').text();
            if (typeof(efy_xml.xmlTagInDb) ==='undefined') efy_xml.xmlTagInDb='';
            efy_xml.tablename = $(this).find('table_name').text();
            if (typeof(efy_xml.tablename) ==='undefined') efy_xml.tablename='';
            if(hdn_columnName === efy_xml.columnName){
                if (hdn_orderby ==='ASC') {
                    classtemp = 'headerasc';
                }else{
                    classtemp = 'headerdesc';
                }
            }
            psHtmlTempLabel += '<td class="sortdb '+classtemp+'" columnName="'+efy_xml.columnName+'" xmldata="'+efy_xml.xmlData+'" xmlTagInDb="'+efy_xml.xmlTagInDb+'" tablename="'+efy_xml.tablename+'" align="center">'+ efy_xml.v_label+'</td>';
        }else{
            psHtmlTempLabel += '<td class="" align="center">'+ efy_xml.v_label+'</td>';
        }
        
    })
    efy_xml.htmlexport += psHtmlTempWidth + '<tr class="header">'+ psHtmlTempLabel + '<tr>';
    // groupcol
    var groupname = $(xml).find('level1groupid').text(),v_default1 = '',function_group = $(xml).find('function_group').text(),groupdisplay='';
    if(groupname ==='')
        groupname = $(xml).find('group_column').text();
    count_column = parseInt($(xml).find('col').length);
    colspan = count_column -1;    
    // var oForm = $(objupdate).closest('form');
    var oForm = $('form#'+frm);
    // Duyet lay text like
    if (addrow && typeof(fulltextsearch) ==='undefined') {
        fulltextsearch = $(oForm).find(':input[column_name="C_DATA_TEMP"]').val();
    };
    // 
    /*var arrSearchLike=[];
    $(xml).find('filter_formfield_expand_list:eq(0) column_name').each(function(){
        // 
        compare_operator = $(this).parent().find('compare_operator').text();
        if (compare_operator ==='like') {
            arrSearchLike[$(this).text()] = $(oForm).find(':input[column_name="'+ $(this).text() +'"]').val();
        };
    })*/
    // alert(arrSearchLike[])
    // window.console.log(arrSearchLike);
    
    for (var i = 0; i < iTotalRecord; i++) {
        // Mark Star
        efy_xml.markstar = arrResult[i]['MARK_STAR'];
        if (typeof(efy_xml.markstar)==='undefined') efy_xml.markstar = 0;
        if(groupname !='' && v_default1 != arrResult[i][groupname]){
            v_default1 = arrResult[i][groupname];
            if (typeof(function_group)!='undefined' && function_group !='') {
                groupdisplay = arrResult[i]['f_'+groupname];
            }else{
                groupdisplay = v_default1;
            }
            efy_xml.htmlexport += '<tr class="tr_group"><td align="CENTER"><input type="checkbox" onclick="selectrow(this);checkgroup(this)" class="groupcol" name="chk_item_group" value="'+ v_default1 +'" /></td>';
            efy_xml.htmlexport += '<td colspan="'+colspan +'"><div class="icon_group_open" onclick="selectgroup(this)">&nbsp;&nbsp;</div><label style="font-weight: bold;">'+ groupdisplay +'</label></td></tr>';
        }
        efy_xml.objectId = arrResult[i][efy_xml.v_pk_column];        
        if (arrResult[i]['Check'] == 'co_mau_hs')
        {                    
            efy_xml.htmlexport += '<tr style="color:blue;" title="Hồ sơ bên tiếp nhận">';    
        }
        else {
            efy_xml.htmlexport += '<tr>';
        }
        //render rows
        $(xml).find('list_body').find('col').each(function(){
            efy_xml.v_width = $(this).find('width').text();
            efy_xml.v_label = $(this).find('label').text();
            v_type = $(this).find('type').text();
            v_type = v_type.toLowerCase();
            efy_xml.v_align = $(this).find('align').text();
            if (typeof(efy_xml.v_align) ==='undefined') efy_xml.v_align='';
            efy_xml.xmlData = $(this).find('xml_data').text();

            if (typeof(efy_xml.xmlData) ==='undefined') efy_xml.xmlData='false';//Default get data in column name
            efy_xml.columnName = $(this).find('column_name').text();
            if (typeof(efy_xml.columnName) ==='undefined') efy_xml.columnName='';            
            efy_xml.alias_name = $(this).find('alias_name').text();
            if (typeof(efy_xml.alias_name) ==='undefined' || efy_xml.alias_name ==='') efy_xml.alias_name=efy_xml.columnName;
            efy_xml.xmlTagInDb = $(this).find('xml_tag_in_db').text();
            if (typeof(efy_xml.xmlTagInDb) ==='undefined') efy_xml.xmlTagInDb='';
            //efy_xml.v_value = arrResult[i][efy_xml.columnName];
            if (typeof(efy_xml.v_value) ==='undefined') efy_xml.v_value='';
            //Xử lý kiểm tra lấy dữ liệu trong column or xml string
            if(efy_xml.xmlData == 'false'){
                efy_xml.v_value = arrResult[i][efy_xml.alias_name];
            }else{
                //get xml string in database
                if (efy_xml.xmlData == 'true'){                
                    xmlString = arrResult[i][efy_xml.alias_name];
                    efy_xml.v_value = efy_xml._xmlGetXmlTagValue(xmlString,"data_list",efy_xml.xmlTagInDb);
                }else{
                ;
                }
            }
            efy_xml.phpfunction = ($(this).find('phpfunction') ? $(this).find('phpfunction').text() : '');
            if (efy_xml.phpfunction !='') {
                efy_xml.v_value = arrResult[i]['f_'+efy_xml.alias_name];
            };

            if(v_type !='checkbox' &&  typeof(fulltextsearch) !='undefined' && fulltextsearch !=''){
                // efy_xml.v_value = efy_xml.v_valuet();
                /*var oText = efy_xml.v_value;
                efy_xml.v_value = oText.replace(/(<([^>]+)>)/ig,"");*/

                /*var oText = $(efy_xml.v_value).text();
                efy_xml.v_value = oText;*/
                var s = new String(efy_xml.v_value);
                if(fulltextsearch.length > 1)
                    efy_xml.v_value = s.searchStringColor(fulltextsearch);
                else
                    efy_xml.v_value = s;
            }
            efy_xml.v_onclick ='';
            efy_xml.v_ondblclick = ($(this).find('event_url') ? $(this).find('event_url').text() : '');
            
            // if (typeof(efy_xml.phpfunction) ==='undefined') efy_xml.phpfunction='';
            efy_xml.htmlexport += efy_xml._generateHtmlForColumn(v_type,i);
        })
        efy_xml.htmlexport += '</tr>';
        
    }
    $(objupdate).html(efy_xml.htmlexport);
    if(addrow){
        //Auto fill row empty in table
        efy_xml.addRowEmpty($('form#'+frm+' table#table-data tbody'),15);
        loadeventsort($('form#'+frm+' table#table-data tbody'),efy_xml.oClass,this.functionload);
        fixTitle(efy_xml.modaldialog,oForm);

    }
    if(this.utilities){
        var oTDCheck = $(objupdate).find('tr.header td:eq(0)');
        $(oTDCheck).click(function(){
            getdatalistfilter($(this),efy_xml.oClass);
        })
        $(oTDCheck).addClass('selectstar');

    }
}
/**
* @author:Truongdv
* @since: 17/12/2012
* @todo: Ham xuat ra chuoi column html
* @param obj: Doi tuong duoc chon
*/
System_Xml.prototype._generateHtmlForColumn = function(v_type,i){
    var htmloutput = '', efy_xml = this, cstar='unstar';
    v_type = v_type.toLowerCase();

    switch(v_type) {
        case "checkbox":
            efy_xml.v_onclick = 'selectrow(this);'+ efy_xml.v_onclick;
            htmloutput += '<td align="'+ this.v_align + '"><input type="checkbox" ondblclick="'+efy_xml.v_ondblclick+'" onclick="{'+efy_xml.v_onclick+'}" name="chk_item_id" value="'+ this.v_value +'" />';
            if(this.utilities){
                cstar = (efy_xml.markstar === 1 ? 'star':'unstar');
                htmloutput  += '<div class="'+cstar+'"></div>';
            }
            htmloutput  += '</td>';
            break;
        case "text":
            efy_xml.v_onclick = 'select_row(this);'+ efy_xml.v_onclick;
            htmloutput += '<td class="data" align="'+ this.v_align +'" ondblclick="'+efy_xml.v_ondblclick+'" onclick="{'+efy_xml.v_onclick+'}">' + ''+ this.v_value +'</td>';
            break;
        //Kiểu date    
        case "date":
            htmloutput += '<td class="data" align="'+ this.v_align +'" ondblclick="'+efy_xml.v_ondblclick+'" onclick="select_row(this)">' + ''+ efy_xml._yyyymmddToDDmmyyyy(this.v_value) +'</td>';
            break;
        case "identity":
            var identity = parseInt(i)+1;
            efy_xml.v_onclick = 'select_row(this);'+ efy_xml.v_onclick;
            htmloutput += '<td class="data" align="'+ this.v_align +'" ondblclick="'+efy_xml.v_ondblclick+'" onclick="{'+efy_xml.v_onclick+'}">' + ''+ identity +'</td>';
            break;
        default:
            htmloutput += this.v_value;
    }
    return htmloutput;
}
/**
* @author:Truongdv
* @since: 17/12/2012
* @todo: Ham xac dinh khi NSD chon 1 row tren man hinh danh sách
* @param obj: Doi tuong duoc chon
*/
function select_row(obj){
    var oTable = $(obj).parent().parent().parent();
    $(oTable).find('td').parent().removeClass('selected');
    $(oTable).find('td').parent().find('input[name="chk_item_id"]').attr('checked',false);
    $(obj).parent().addClass('selected');
    $(obj).parent().find('input[name="chk_item_id"]').attr('checked',true);
}
//Them row trong
System_Xml.prototype.addRowEmpty = function(obj,num){
    var numRow = $(obj).children().length - 2, numCol = $(obj).children(':first-child').children().length, shtml = '';	
    if(numRow < num){		
        for(var i = 0; i < (num - numRow); i++){
            shtml += '<tr>';
            for(var j =0; j < numCol; j++){
                shtml += '<td>&nbsp;</td>';
            }
            shtml += '</tr>';
        }
        $(obj).append(shtml);
    }
}
function selectgroup(obj){
    var classStyle = '',v_group='',flag = false;
    var group_value = $(obj).parent().parent().find('input[type="checkbox"][name="chk_item_group"]').val();
    var oTableCurrent = $(obj).parent().parent().parent().parent();
    var data = getAllIndex(group_value);
    var startIndex = data.startIndex;
    var endIndex = data.endIndex;
    // alert(startIndex+'----'+endIndex);
    if($(obj).hasClass('icon_group_open')){
        $(obj).addClass('icon_group_close');
        $(obj).removeClass('icon_group_open');
        for (var i = startIndex +1; i < endIndex; i++) {
            $(oTableCurrent).find('tr:eq('+i+')').hide();
        };
    }else{
        $(obj).addClass('icon_group_open');
        $(obj).removeClass('icon_group_close');
        for (var i = startIndex+1; i < endIndex; i++) {
            $(oTableCurrent).find('tr:eq('+i+')').show();
        };
    }
}
// 
function checkgroup(obj){
    var group_value = $(obj).val();
    var data = getAllIndex(group_value);
    var oTableCurrent = $(obj).parent().parent().parent().parent();
    var checked = (obj.checked ? true:false);
    var objtr ='',flag=false;
    for (var i = data.startIndex+1; i < data.endIndex; i++) {
        objtr = $(oTableCurrent).find('tr:eq('+i+')');
        flag =false;
        objtr.find('input[type="checkbox"][name="chk_item_id"]').each(function(){
            if ($(this).is(':disabled')=== false){
                $(this).attr('checked',checked);
                flag = true;
            }
        })
        if(checked && flag){
            objtr.addClass('selected');
        }else{
            objtr.removeClass('selected');
        }
    };
}
function getAllIndex(group_value){
    var startIndex =0;
    var endIndex =0;
    var index =0;
    $('table.list-table-data tr').each(function(){
        if($(this).hasClass('tr_group')){
            v_group = $(this).find('input[type="checkbox"][name="chk_item_group"]').val();
            if (v_group === group_value)
                startIndex = $(this).index();
            if(v_group != group_value && startIndex != 0 && endIndex === 0)
                endIndex = $(this).index();
        }
        if($(this).find('input[type="checkbox"]').length >0)
            index = $(this).index();
    })
    if(endIndex ===0)
        endIndex = index+1;
    return data={
        startIndex:startIndex,
        endIndex:endIndex
    };
}
/**
* @author:Truongdv
* @since: 23/05/2013
* @todo: Load cac su kien click vao header de sap xep
* @param obj: Doi tuong duoc chon
*/
function loadeventsort(obj,myClass,functionload){    
    if (typeof(functionload)==='undefined') {
        functionload = 'myClass.loadList()';
    };
    // alert($(obj).closest("form").attr('id'));
    $(obj).find('td.sortdb').disableSelection();
    $(obj).find('td.sortdb').click(function(){
        var columnName = $(this).attr('columnName');
        var tablename = $(this).attr('tablename');
        var xmldata = $(this).attr('xmldata');
        var xmltagindb = $(this).attr('xmltagindb');
        var orderby ='';
        if($(this).hasClass('headerdf')){
            refreshclass(obj,$(this));
            $(this).removeClass('headerdf');
            $(this).addClass('headerasc');
            orderby = 'ASC';
        }else{
            if($(this).hasClass('headerasc')){
                refreshclass(obj,$(this));
                $(this).removeClass('headerasc');
                $(this).addClass('headerdesc');
                orderby = 'DESC';
            }else{
                refreshclass(obj,$(this));
                $(this).removeClass('headerdesc');
                $(this).addClass('headerasc'); 
                orderby = 'ASC';
            }
        }
        var sFormID = $(obj).closest("form").attr('id');
        var sHtmlSort = '<input type="hidden" name="hdn_columnName" id="hdn_columnName" value="'+columnName+'" />';
        sHtmlSort += '<input type="hidden" name="hdn_tablename" id="hdn_tablename" value="'+tablename+'" />';
        sHtmlSort += '<input type="hidden" name="hdn_xmldata" id="hdn_xmldata" value="'+xmldata+'" />';
        sHtmlSort += '<input type="hidden" name="hdn_xmltagindb" id="hdn_xmltagindb" value="'+xmltagindb+'" />';
        sHtmlSort += '<input type="hidden" name="hdn_orderby" id="hdn_orderby" value="'+orderby+'" />';
        if($('div#paramesearch').length >0){
            $('div#paramesearch').html(sHtmlSort);
        }else{
            sHtmlSort = '<div id="paramesearch">'+sHtmlSort+'</div>';
            $(obj).closest("form").append(sHtmlSort);
        }
        eval(functionload);
    })
}
function refreshclass(obj,oCurrent){
    $(obj).find('td.sortdb').removeClass('headerasc,headerdesc');
    $(obj).find('td.sortdb').addClass('headerdf');
    oCurrent.removeClass('headerdf');
}
function loadmenudropdown(){
    $(".menudropdown").each(function(){
        menudropdown($(this));
    })
}